<?php
namespace Service;

class User extends Base
{

    public function getDatabase()
    {
        return $this->get(DATABASE_USER);
    }

    public function decrypt($user)
    {
        $coreEncrypt = $this->get(CORE_ENCRYPT);
        if(!empty($user->dry_phone)){
            $user->dry_phone = $coreEncrypt->setKey('sensitive')->decrypt($user->dry_phone);
        }
        if(!empty($user->dry_email)){
            $user->dry_email = $coreEncrypt->setKey('sensitive')->decrypt($user->dry_email);
        }
        return $user;
    }

    public function getUserByUsernameOrPhone($username, $phone)
    {
        $database = $this->getDatabase();
        return $database->getUserByUsernameOrPhone($username, $phone);
    }

    public function getUserByPhonePlus($phone)
    {
        $coreEncrypt = $this->get(CORE_ENCRYPT);
        $phone = $coreEncrypt->setKey('sensitive')->encrypt($phone);
        $username = $phone;
        return $this->getUserByUsernameOrPhone($username, $phone);
    }

    public function loginByPassword($usernameOrPhone, $password)
    {
        $coreEncrypt = $this->get(CORE_ENCRYPT);
        $corePassword = $this->get(CORE_PASSWORD);
        $username = $usernameOrPhone;
        $phone = $coreEncrypt->setKey('sensitive')->encrypt($usernameOrPhone);
        $user = $this->getUserByUsernameOrPhone($username, $phone);
        /*用户不存在*/
        if(empty($user)){
            return makeFail('USERNAME_NOT_EXIST');
        }
        /*密码不正确*/
        if(!$corePassword->passwordVerify($password, $user->dry_password)){
            return makeFail('USERNAME_OR_PASSWORD_ERROR');
        }
        /*用户被禁用*/
        if($user->dry_status == 0){
            return makeFail('USERNAME_STATUS_ERROR');
        }
        /*返回用户*/
        return $this->decrypt($user);
    }

    public function makeToken($id = 0)
    {
        $timestamp = getTimestamp();
        $data = "{$id}-{$timestamp}";
        $coreEncrypt = $this->get(CORE_ENCRYPT);
        return base64_encode($coreEncrypt->encrypt($data));
    }

    public function setToken($device, $userId)
    {
        /*根据用户id生成token*/
        $token = $this->makeToken($userId);
        /*写入缓存*/
        $this->get(CACHE_USERTOKEN)->setToken($device, $userId, $token);
        return $token;
    }

    public function getToken($device, $userId)
    {
        return $this->get(CACHE_USERTOKEN)->getToken($device, $userId);
    }

    public function deleteToken($device, $userId)
    {
        return $this->get(CACHE_USERTOKEN)->deleteToken($device, $userId);
    }

    /*验证是不是一个加密的token，并且判断是否存在*/
    public function validToken($device, $token = '')
    {
        $result = $this->get(CORE_ENCRYPT)->decrypt(base64_decode($token));
        if($result == false){
            return false;
        }
        $temp = explode('-', $result);
        $userId = $temp[0];
        /*检查cache*/
        $find = $this->get(CACHE_USERTOKEN)->getToken($device, $userId);
        if(!$find){
            return false;
        }
        /*是否一致*/
        if($find != $token){
            return false;
        }
        /**/
        return [
            'id' => $userId,
            'timestamp' => $temp[1],
            'time' => date('Y-m-d H:i:s', $temp[1])
        ];
    }

    /*验证token参数传递并且正确*/
    public function checkToken($data, $device)
    {
        if(notSetOrEmpty($data, 'token')){
            return false;
        }
        $token = $data['token'];
        $result = $this->validToken($device, $token);
        if(!$result){
            return false;
        }
        return $result['id'];
    }

    public function getUserFromToken($device, $token)
    {
        $result = $this->validToken($device, $token);
        if(!$result){
            return false;
        }
        $user = $this->one($result['id']);
        $user = $this->decrypt($user);
        $user->ext_phone = getSensitivePhone($user->dry_phone);
        $user->ext_nick_name = $user->id;
        $user->ext_avatar_url = '/images/avatar.png';
        if(!empty($user->dry_wei_xin_sp_user_info)){
            $temp = json_decode($user->dry_wei_xin_sp_user_info);
            $user->ext_nick_name = $temp->nickName;
            $user->ext_avatar_url = $temp->avatarUrl;
        }
        return $user;
    }

    public function weiXinSpAdd($phone, $openId, $userInfo = '')
    {
        $coreEncrypt = $this->get(CORE_ENCRYPT);
        $phone = $coreEncrypt->setKey('sensitive')->encrypt($phone);
        return $this->getDatabase()->weiXinSpAdd($phone, $openId, $userInfo);
    }

    public function updatePassword($userId, $password)
    {
        $database = $this->getDatabase();
        $passwordEncrypt = $this->get(CORE_PASSWORD)->passwordHash($password);
        $update = [
            'dry_password' => $passwordEncrypt
        ];
        return $database->update($update, $userId);
    }

    public function addUserAccountInformation($user)
    {
        $userAccount = $this->get(SERVICE_USERACCOUNT)->one($user->id);
        $object = object();
        $object->dry_balance = '0.00';
        $object->dry_total = '0.00';
        if($userAccount){
            $object->dry_balance = bcadd($userAccount->dry_balance, 0, 2);
            $object->dry_total = bcadd($userAccount->dry_total, 0, 2);
        }
        $user->ext_user_account = $object;
        return $user;
    }

    public function addUserIncomeInformation($user)
    {
        $total = $this->get(SERVICE_USERINCOMELOG)->getSum($user->id, '', '', '', '');
        $object = object();
        $object->dry_total = $total;
        $user->ext_user_income = $object;
        return $user;
    }

    public function addUserCodeInformation($user)
    {
        $object = object();
        $object->code = makeUserCode($user->id);
        $object->note = [
            '1. 优惠码全部为大写字母。',
            '2. 优惠码是根据用户ID生成的。',
            '3. 用户使用您的优惠码购买商品有一定的优惠，同时您能获得一定的分成。',
            '4. 某些商品您需要购买代理资格后优惠码才会生效，如果优惠码没有生效，用户使用您的优惠码没有优惠，您也没有分成。'
        ];
        $user->ext_user_code = $object;
        return $user;
    }

}